package database

import (
	"context"
	"database/sql"
	"fmt"
	"quipus/internal/database/dao"
	"quipus/internal/database/postgres"
	"quipus/internal/profile"

	"log"
	"strconv"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib"
	_ "github.com/joho/godotenv/autoload"
	"github.com/pkg/errors"
)

type DB struct {
	db        *sql.DB
	profile   *profile.Profile
	dbType    string
	dbHandler dao.DBOperator
}

func (d *DB) Type() string {
	return d.dbType
}

func (d *DB) GetDB() *sql.DB {
	return d.db
}

func (d *DB) Close() error {
	return d.db.Close()
}

func (d *DB) Health() map[string]string {
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()

	stats := make(map[string]string)

	// Ping the database
	err := d.db.PingContext(ctx)
	if err != nil {
		stats["status"] = "down"
		stats["error"] = fmt.Sprintf("db down: %v", err)
		log.Fatalf(fmt.Sprintf("db down: %v", err)) // Log the error and terminate the program
		return stats
	}

	// Database is up, add more statistics
	stats["status"] = "up"
	stats["message"] = "It's healthy"

	// Get database stats (like open connections, in use, idle, etc.)
	dbStats := d.db.Stats()
	stats["open_connections"] = strconv.Itoa(dbStats.OpenConnections)
	stats["in_use"] = strconv.Itoa(dbStats.InUse)
	stats["idle"] = strconv.Itoa(dbStats.Idle)
	stats["wait_count"] = strconv.FormatInt(dbStats.WaitCount, 10)
	stats["wait_duration"] = dbStats.WaitDuration.String()
	stats["max_idle_closed"] = strconv.FormatInt(dbStats.MaxIdleClosed, 10)
	stats["max_lifetime_closed"] = strconv.FormatInt(dbStats.MaxLifetimeClosed, 10)

	// Evaluate stats to provide a health message
	if dbStats.OpenConnections > 40 { // Assuming 50 is the max for this example
		stats["message"] = "The database is experiencing heavy load."
	}

	if dbStats.WaitCount > 1000 {
		stats["message"] = "The database has a high number of wait events, indicating potential bottlenecks."
	}

	if dbStats.MaxIdleClosed > int64(dbStats.OpenConnections)/2 {
		stats["message"] = "Many idle connections are being closed, consider revising the connection pool settings."
	}

	if dbStats.MaxLifetimeClosed > int64(dbStats.OpenConnections)/2 {
		stats["message"] = "Many connections are being closed due to max lifetime, consider increasing max lifetime or revising the connection usage pattern."
	}

	return stats
}

// NewDBDriver creates new db driver based on profile.
func NewDBDriver(profile *profile.Profile) (dao.Driver, dao.DBOperator, error) {
	var driver dao.Driver
	var err error
	var db *sql.DB
	var handler dao.DBOperator
	switch profile.Driver {
	case "postgres":
		handler, db, err = postgres.NewDB(profile)
	default:
		return nil, nil, errors.New("unknown db driver")
	}
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to create db driver")
	}

	driver = &DB{db: db, profile: profile, dbType: profile.Driver, dbHandler: handler}
	return driver, handler, nil
}
